package chartCraft.tableDesk;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JSlider;

import chartCraft.ChartCraftController;
import chartCraft.Log;
import chartCraft.model.TopModel;
import chartCraft.model.Model.NotifyingMessage;

public class TimeSlider extends JSlider implements Observer{
	
	private ChartCraftController mChartCraftController;
	private TopModel mTopModel;

	public TimeSlider(ChartCraftController chartCraftController, TopModel topModel) {
		mChartCraftController = chartCraftController;
		setModel(topModel);
		
		setMinimum(0);
		setMajorTickSpacing(1);
		setPaintTicks(true);
		setSnapToTicks(true);

		
		updateMinAndMax();
		int currentTime = mTopModel.getCurrentTimeId();
		super.setValue(currentTime);
	}
	
	public void setModel(TopModel model) {
		mTopModel = model;
		mTopModel.addObserver(this);
	}
	
	
	private void updateMinAndMax() {
		int maxTime = mTopModel.getNoOfTime(); //so the time starts with 1 in the UI
		setMaximum(maxTime-1);
				
		if (getMinimum() == getMaximum()) {
			setEnabled(false);
		} else {
			setEnabled(true);
		}
	}

	@Override
	public void setValue(int n) {
		if (mTopModel.getCurrentTimeId() != n) {
			//change time only when it is changed 
			//to reduce no. of notification
			mChartCraftController.changeTimeTo(n);
		}
	}
	
	private void refreshSlider() {
		if (mTopModel.isPlaying()) {
			super.setEnabled(false);
			int currentTime = (int) Math.round(mTopModel.getFrameNo());
			super.setValue(currentTime);
			super.fireStateChanged();
		} else {
			super.setEnabled(true);
			int currentTime = mTopModel.getCurrentTimeId();
			super.setValue(currentTime);
			super.fireStateChanged();
		}
		
	}

	@Override
	public void update(Observable o, Object arg1) {
		
		if (o == mTopModel) {
			NotifyingMessage msg = (NotifyingMessage) arg1;
			String action = msg.getAction();
			
			if (action == TopModel.CURRENT_TIME_UPDATED) {
				refreshSlider();
			} else if (action == TopModel.NO_OF_TIME_UPDATED) {
				updateMinAndMax();
				super.fireStateChanged();
			} else if (action == TopModel.PLAY_FRAME_NO_CHANGED) {
				refreshSlider();
			} else if (action == TopModel.PLAY_STATUS_CHANGED) {
				refreshSlider();
			}
		}
	}
}